package org.example.springboot.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.example.springboot.DTO.UserRegisterDTO;
import org.example.springboot.common.Result;
import org.example.springboot.entity.User;
import org.example.springboot.DTO.UserPasswordUpdateDTO;
import org.example.springboot.service.UserService;
import org.example.springboot.util.JwtTokenUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 用户管理控制器
 */
@Tag(name="用户管理接口")
@RestController
@RequestMapping("/user")
public class UserController {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);
    
    @Resource
    private UserService userService;

    @Operation(summary = "获取当前登录用户信息")
    @GetMapping("/current")
    public Result<?> getCurrentUser() {
        User currentUser = JwtTokenUtils.getCurrentUser();
        if (currentUser == null) {
            return Result.error("获取当前用户信息失败，请确保已登录");
        }
        // 返回前清除密码等敏感信息
        currentUser.setPassword(null);
        return Result.success(currentUser);
    }

    @Operation(summary = "用户注册")
    @PostMapping("/register")
    public Result<?> register(@RequestBody @Valid UserRegisterDTO registerDTO) {
        Long userId = userService.register(registerDTO);
        return Result.success("注册成功", userId);
    }

    @Operation(summary = "根据id获取用户信息")
    @GetMapping("/{id}")
    public Result<?> getById(@PathVariable Long id) {
        // 如果用户不存在会抛出异常，由全局异常处理器处理
        User user = userService.getUserById(id);
        // 返回前清除密码等敏感信息
        user.setPassword(null);
        return Result.success(user);
    }

    @Operation(summary = "根据username获取用户信息")
    @GetMapping("/username/{username}")
    public Result<?> getUserByUsername(@PathVariable String username) {
        // 不存在的用户会抛出异常
        User user = userService.getByUsername(username);
        // 返回前清除密码等敏感信息
        user.setPassword(null);
        return Result.success(user);
    }

    @Operation(summary = "登录")
    @PostMapping("/login")
    public Result<?> login(@RequestBody User user) {
        User loginUser = userService.login(user);
        // 返回前清除密码等敏感信息
        loginUser.setPassword(null);
        return Result.success(loginUser);
    }

    @Operation(summary = "修改个人信息")
    @PutMapping("/profile/{id}")
    public Result<?> updateProfile(@PathVariable Long id, @RequestBody User user) {
        // 仅允许修改基本信息，不能修改角色等敏感信息
        User updateUser = new User();
        updateUser.setName(user.getName());
        updateUser.setPhone(user.getPhone());
        updateUser.setEmail(user.getEmail());
        updateUser.setAvatar(user.getAvatar());
        
        // 如果传入了邮箱则可以修改邮箱
        if (user.getEmail() != null) {
            updateUser.setEmail(user.getEmail());
        }
        
        userService.updateUser(id, updateUser);
        return Result.success("个人信息修改成功");
    }
    
    @Operation(summary = "密码修改")
    @PutMapping("/password/{id}")
    public Result<?> updatePassword(@PathVariable Long id, @RequestBody @Valid UserPasswordUpdateDTO userPasswordUpdate) {
        // 密码修改失败会抛出异常
        userService.updatePassword(id, userPasswordUpdate);
        return Result.success("密码修改成功");
    }

    @Operation(summary = "忘记密码")
    @GetMapping("/forget")
    public Result<?> forgetPassword(@RequestParam(required = false) String email, 
                                   @RequestParam(required = false) Long userId, 
                                   @RequestParam String newPassword) {
        // 密码重置失败会抛出异常
        if (userId != null) {
            // 通过用户ID重置密码
            userService.resetPasswordById(userId, newPassword);
        } else if (email != null && !email.isEmpty()) {
            // 通过邮箱重置密码
            userService.forgetPassword(email, newPassword);
        } else {
            return Result.error("请提供用户ID或邮箱");
        }
        return Result.success("密码重置成功");
    }

    @Operation(summary = "分页查询用户")
    @GetMapping("/page")
    public Result<?> getUsersByPage(
            @RequestParam(defaultValue = "") String username,
            @RequestParam(defaultValue = "") String sex,
            @RequestParam(defaultValue = "") String name,
            @RequestParam(defaultValue = "") String roleType,
            @RequestParam(defaultValue = "1") Integer currentPage,
            @RequestParam(defaultValue = "10") Integer size) {
        Page<User> page = userService.getUsersByPage(username, sex, name, roleType, currentPage, size);
        
        // 清除所有用户的密码
        page.getRecords().forEach(user -> user.setPassword(null));
        
        return Result.success(page);
    }

    @Operation(summary = "根据角色获取用户列表")
    @GetMapping("/role/{roleType}")
    public Result<?> getUserByRole(@PathVariable String roleType) {
        List<User> users = userService.getUserByRole(roleType);
        
        // 清除所有用户的密码
        users.forEach(user -> user.setPassword(null));
        
        return Result.success(users);
    }

    @Operation(summary = "批量删除用户")
    @PostMapping("/batch-delete")
    public Result<?> deleteBatch(@RequestBody Map<String, List<Integer>> params) {
        List<Integer> ids = params.get("ids");
        if (ids == null || ids.isEmpty()) {
            return Result.error("未选择要删除的用户");
        }
        
        userService.deleteBatch(ids);
        return Result.success("批量删除成功");
    }

    @Operation(summary = "获取所有用户")
    @GetMapping("/all")
    public Result<?> getUserList() {
        List<User> list = userService.getUserList();
        
        // 清除所有用户的密码
        list.forEach(user -> user.setPassword(null));
        
        return Result.success(list);
    }

    @Operation(summary = "创建新用户")
    @PostMapping("/add")
    public Result<?> createUser(@RequestBody @Valid User user) {
        userService.createUser(user);
        return Result.success("创建成功");
    }

    @Operation(summary = "更新用户信息")
    @PutMapping("/{id}")
    public Result<?> updateUser(@PathVariable Long id, @RequestBody User user) {
        // 更新失败会抛出具体原因的异常
        userService.updateUser(id, user);
        return Result.success("更新成功");
    }

    @Operation(summary = "根据id删除用户")
    @DeleteMapping("/delete/{id}")
    public Result<?> deleteUserById(@PathVariable Long id) {
        // 删除失败会抛出异常
        userService.deleteUserById(id);
        return Result.success("删除成功");
    }
    
    @Operation(summary = "更新用户状态")
    @PutMapping("/{id}/status")
    public Result<?> updateUserStatus(@PathVariable Long id, @RequestParam Integer status) {
        User user = new User();
        user.setStatus(status);
        userService.updateUser(id, user);
        return Result.success("状态更新成功");
    }

}
